package akbderby.page;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import org.slim3.controller.Navigation;
import org.slim3.datastore.Datastore;
import org.slim3.util.BeanUtil;

import scenic3.annotation.ActionPath;
import scenic3.annotation.Default;
import scenic3.annotation.Page;
import scenic3.annotation.Var;
import akbderby.model.Question;
import akbderby.model.Quiz;

import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;

@Page("/quiz")
public class QuizPage extends QuizBasePage {

    @ActionPath("logon")
    public Navigation logon() {
        if (!isNull(getUser())) {
            return redirect(basePath);
        } else {
            try {
                UserService userService = UserServiceFactory.getUserService();
                response.sendRedirect(userService.createLoginURL(request
                    .getRequestURI()));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    @ActionPath("create")
    public Navigation create() {

        if (!isNull(getUser())) {
            return forward("create.jsp");
        } else {
            try {
                UserService userService = UserServiceFactory.getUserService();
                response.sendRedirect(userService.createLoginURL(request
                    .getRequestURI()));
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return null;
    }

    @ActionPath("editList")
    public Navigation editList() {
        if (!getUser().isAuthentication()) {
            return forward("error.jsp");
        }
        Quiz quiz = getQuiz();
        if (isNull(quiz)) {
            return forward("error.jsp");
        }
        setQuizKeyWithSession(quiz.getKey());
        requestScope("quiz", quiz);
        requestScope("questions", quiz.getQuesionListRef().getModelList());
        return forward("/quiz/editList.jsp");
    }

    @ActionPath("addQuiz")
    public Navigation addQuiz() {
        if (!getUser().isAuthentication()) {
            return forward("error.jsp");
        }
        Quiz quiz = new Quiz();
        BeanUtil.copy(request, quiz);
        quiz.setUserData(getUser());
        quiz.setCreateDate(new Date());

        Datastore.put(quiz);
        setQuizKeyWithSession(quiz.getKey());
        return redirect("editList");
    }

    @ActionPath("editQuestion/{questionNo}")
    public Navigation edit(@Var("questionNo") int questionNo) {
        List<Question> questions = getQuestions();
        if (isEmpty(questions)) {
            questionNo = 1;
        } else {
            boolean existence = false;
            for (Question q : questions) {
                if (questionNo == q.getQuestionNo()) {
                    BeanUtil.copy(q, request);
                    existence = true;
                    break;
                }
            }
            if (!existence) {
                questionNo = questions.size() + 1;
            }
        }
        requestScope("questionNo", questionNo);
        return forward("/quiz/addQuestion.jsp");
    }

    @ActionPath("addQuestion/{questionNo}")
    public Navigation addQuestion(@Var("questionNo") int questionNo) {
        if (!getUser().isAuthentication()) {
            return forward("error.jsp");
        }

        Quiz quiz = getQuiz();
        if (isNull(quiz)) {
            return forward("error.jsp");
        }

        Question question = getQuestion(quiz, questionNo);
        if (isNull(question)) {
            question = new Question();
            question.getQuizRef().setModel(quiz);
        }
        BeanUtil.copy(request, question);

        Datastore.put(question);

        return redirect("/quiz/editList");
    }

    @ActionPath("deleteQuestion/{questionNo}")
    public Navigation deleteQuestion(@Var("questionNo") int questionNo) {
        if (!getUser().isAuthentication()) {
            return forward("error.jsp");
        }

        Question question = getQuestion(questionNo);
        if (isNull(question)) {
            return forward("error.jsp");
        }

        Datastore.delete(question.getKey());

        List<Question> questions = getQuestions();
        if (!isEmpty(questions)) {
            int wQuestionNo = 1;
            for (Question q : questions) {
                q.setQuestionNo(wQuestionNo);
                wQuestionNo++;
            }
            Datastore.put(questions);
        }
        return redirect("/quiz/editList");
    }

    @ActionPath("load/{id}")
    public Navigation load(@Var("id") String id) {
        if (!getUser().isAuthentication()) {
            return forward("error.jsp");
        }
        Quiz quiz = getQuiz(id);
        if (isNull(quiz)) {
            return forward("error.jsp");
        }
        setQuizKeyWithSession(quiz.getKey());
        return redirect("/quiz/editList");
    }

    @ActionPath("release")
    public Navigation release() {
        if (!getUser().isAuthentication()) {
            return forward("error.jsp");
        }
        Quiz quiz = getQuiz();
        if (isNull(quiz)) {
            return forward("error.jsp");
        }
        quiz.setReleased(true);
        Datastore.put(quiz);
        return redirect("/quiz/editList");
    }

    @ActionPath("doPrivate")
    public Navigation doPrivate() {
        if (!getUser().isAuthentication()) {
            return forward("error.jsp");
        }
        Quiz quiz = getQuiz();
        if (isNull(quiz)) {
            return forward("error.jsp");
        }
        quiz.setReleased(false);
        Datastore.put(quiz);
        return redirect("/quiz/editList");
    }

    // @ActionPath("register")
    // public Navigation register() {
    // User user = getUser();
    // if (isNull(user)) {
    // return forward("error.jsp");
    // }
    // Quiz quiz = (Quiz) sessionScope("quiz");
    // List<Question> questions = sessionScope("questions");
    // Datastore.put(quiz);
    // Datastore.put(questions);
    // return redirect("/quiz/editList");
    // }

    // @ActionPath("edit/{id}")
    // public Navigation show(@Var("id") String id) throws Exception {
    // // if (!GUser().isAuthentication())
    // // return redirect("/");
    // Key key = KeyFactory.stringToKey(id);
    // return null;
    // }

    @Default
    public Navigation index() {
        return forward("index.jsp");
    }
}
